package com.example.griddemo.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.griddemo.R;
import com.example.griddemo.viewmodel.GrouponGoods;

import java.util.List;

public class GrouponAdapter extends RecyclerView.Adapter<GrouponAdapter.ViewHolder> {
    private Context context;
    private List<GrouponGoods> dataList;

    public GrouponAdapter(Context context, List<GrouponGoods> dataList) {
        this.context = context;
        this.dataList = dataList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context)
                .inflate(R.layout.item_groupon, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        GrouponGoods item = dataList.get(position);

        Glide.with(context)
                .load(item.getPicUrl())
                .into(holder.ivImage);

        holder.tvName.setText(item.getName());
        holder.tvPrice.setText(String.format("¥%.2f", item.getRetailPrice()));
        holder.tvGrouponPrice.setText(String.format("团购价¥%.2f", item.getGrouponPrice()));
        holder.tvDiscount.setText(String.format("立减¥%d", item.getGrouponDiscount()));
    }

    @Override
    public int getItemCount() {
        return dataList != null ? dataList.size() : 0;
    }

    public void updateData(List<GrouponGoods> newData) {
        this.dataList = newData;
        notifyDataSetChanged();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        ImageView ivImage;
        TextView tvName;
        TextView tvPrice;
        TextView tvGrouponPrice;
        TextView tvDiscount;

        ViewHolder(View itemView) {
            super(itemView);
            ivImage = itemView.findViewById(R.id.iv_groupon_image);
            tvName = itemView.findViewById(R.id.tv_groupon_name);
            tvPrice = itemView.findViewById(R.id.tv_original_price);
            tvGrouponPrice = itemView.findViewById(R.id.tv_groupon_price);
        }
    }
}